import globalData from '../utils/global.js'
import log from '../utils/log.js'
import {
    toast
} from '../utils/util.js'

export default class Socket{
    constructor(url,callback) {
        console.log(url, 'socket获取url')
        if(!/ws/.test(url)){
            url = globalData.wsUrl + url
        }
        this.wsUrl = url
        this.callback = callback
        this.errNum = 0
        this.connect()
    }
    connect(){
        return new Promise((resolve,reject)=>{
            console.log('Wx ' + globalData.token)
            this.task = wx.connectSocket({
                url: this.wsUrl,
                header: {
                    Authorization: 'Wx ' + globalData.token
                },
                success: ()=>{
                    console.log('长连接建立成功！')
                    resolve()
                },
                fail: (err)=>{
                    toast('长连接建立失败！')
                    log.info('长连接建立失败！', err)
                    log.info('长连接建立失败！' + err.errMsg)

                    console.log('长连接建立失败！',err)
                    reject()
                }
            })
            console.log(this.task)
            this.taskOn()
        })
        
    }
    taskOn(){
        this.task.onOpen(res=>{
            console.log('socket连接成功，开始心跳',res)
            this.heartBeat()
        })
        this.task.onError(err=>{
            console.log('socket连接错误',err)
            // toast('长连接建立失败：'+err.errMsg)
            setTimeout(() => { // 连接发生错误，三秒后重新建立连接
                this.errNum += 1
                if(this.errNum === 6){ // 最多重试6次
                    toast('长连接发生错误！')
                    return 
                }
                this.connect()
            }, 3000)
        })
        this.task.onClose(res=>{
            console.log('socket连接关闭',res)
            // 小程序切换到后台，被微信杀掉，需要重连连接
            if (res.code == 1000 && res.reason == 'interrupted') {
                this.connect()
                return 
            }
            if (res.code == 1001) {
                // 服务端主动关闭SOCKET请求，重新建立链接
                this.connect()
                return 
            }
            // 结束socket
            this.close()
        })
        this.task.onMessage(res=>{
            console.log('socket收到消息',res)
            this.callback(res)
        })
    }
    send(data){
        this.task.send({data})
    }
    close(){
        console.log('socket连接关闭')
        this.task.close()
        this.stopHeart()
    }
    heartBeat(){
        this.heart = setInterval(()=>{
            this.send('ping')
        },30000)
    }
    stopHeart(){
        clearInterval(this.heart)
    }
}

// export default new Socket(globalData.baseUrl)